package org.jeecg.common.nc.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.jeecg.common.nc.enums.WSEnum;
import org.jeecg.common.nc.vo.WSVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Iterator;


public class NCWebService {

    private static final Logger logger = LoggerFactory.getLogger(NCWebService.class);

    // "NC服务器地址"
//    private static final String serverpath = "http://10.10.30.34:8888";

    /**
     * 调用webservice接口,发送数据
     *
     * @param serverpath nc服务器地址 -- http://10.10.30.34:66666
     * @param wsEnum nc接口枚举类
     * @param context 推送内容 json格式串
     * @return
     * @throws Exception
     */
    public static WSVO sendToWS(String serverpath, WSEnum wsEnum, String context) throws Exception {

            ServiceClient serviceClient = new ServiceClient();
            //创建服务地址WebService的URL,注意不是WSDL的URL
            String url = serverpath + "/uapws/service/expenseAccount";
            EndpointReference targetEPR = new EndpointReference(url);
            Options options = serviceClient.getOptions();
            options.setTo(targetEPR);
            //确定调用方法（wsdl 命名空间地址 (wsdl文档中的targetNamespace) 和 方法名称 的组合）
            options.setAction("http://schemas.xmlsoap.org/wsdl/soap/");

            OMFactory fac = OMAbstractFactory.getOMFactory();
            //指定命名空间
            OMNamespace omNs = fac.createOMNamespace("http://ws.service.itf.nc/IExpenseAccountAndBillWs", "ns0");
            OMNamespace omNs2 = fac.createOMNamespace("", "");
            // 指定方法
            OMElement method = fac.createOMElement(wsEnum.getCode(), omNs);

            // 指定方法的参数
            OMElement context_e = fac.createOMElement("string", omNs2);
            context_e.setText(context);
            method.addChild(context_e);
            method.build();
//            saveLog("调用NC接口推送" + wsEnum.getName(), StrUtil.toString(method));
            //远程调用web服务
            OMElement result = serviceClient.sendReceive(method);
            WSVO vo = getReturn(result, wsEnum);

/*            if (!vo.getStatus()) {
                logger.error("method", method.toString());
                logger.error("result",result.toString());
                saveLog("调用NC接口推送" + wsEnum.getName() + "失败，返回参数：", StrUtil.toString(result));
            } else {
                saveLog("调用NC接口推送" + wsEnum.getName() + "成功，返回参数：", StrUtil.toString(result));
            }*/

            return vo;

    }

    /**
     *
     * 调用webservice接口获取数据
     *
     * @param serverpath nc服务器地址 -- http://10.10.30.34:6666
     * @param wsEnum 接口枚举类
     * @param strTs 最后同步时间 "2008-01-01 00:00:00"
     * @return
     */
    public static WSVO getFromWS(String serverpath,WSEnum wsEnum, String strTs) throws Exception{

            ServiceClient serviceClient = new ServiceClient();
            //创建服务地址WebService的URL,注意不是WSDL的URL
            String url = serverpath + "/uapws/service/nc.itf.service.ws.IQueryBillWs";
            EndpointReference targetEPR = new EndpointReference(url);
            Options options = serviceClient.getOptions();
            options.setTo(targetEPR);
            //确定调用方法（wsdl 命名空间地址 (wsdl文档中的targetNamespace) 和 方法名称 的组合）
            options.setAction("http://schemas.xmlsoap.org/wsdl/soap/");

            OMFactory fac = OMAbstractFactory.getOMFactory();
            //指定命名空间
            OMNamespace omNs = fac.createOMNamespace("http://ws.service.itf.nc/IQueryBillWs", "ns0");
            OMNamespace omNs2 = fac.createOMNamespace("", "");
            // 指定方法
            OMElement method = fac.createOMElement(wsEnum.getCode(), omNs);

            // 指定方法的参数
            OMElement group = fac.createOMElement("string", omNs2);
//            group.setText("T1");
            if (wsEnum.getName().equals("用户")) {
                group.setText(wsEnum.getMsg());
            } else {
                group.setText("T1");
            }

            OMElement ts = fac.createOMElement(wsEnum.getTsname(), omNs2); // 同步时间
            ts.setText(strTs);
            method.addChild(group);
            if (wsEnum.getTsname().equals("string2")) {
                OMElement org = fac.createOMElement("string1", omNs2);
                org.setText("");
                if (wsEnum.getName().equals("用户")) {
                    org.setText("BX");
                }
                if(wsEnum.getName().equals("人员")){
                    org.setText(wsEnum.getMsg());
                }
                if(wsEnum.getName().equals("收支项目")){
                    org.setText(wsEnum.getMsg());
                }
                if(wsEnum.getName().equals("收支项目使用权")){
                    org.setText(wsEnum.getMsg());
                }
                if(wsEnum.getName().equals("税率")){
                    org.setText(wsEnum.getMsg());
                }
                if(wsEnum.getName().equals("供应商财务信息")){
                    org.setText(wsEnum.getMsg());
                }
                method.addChild(org);
            }

            method.addChild(ts);
            method.build();
            logger.info("weservice参数：{}",method);
            //远程调用web服务
            OMElement result = serviceClient.sendReceive(method);
            logger.info("weservice接口返回：{}",result);
            WSVO vo = getReturn(result, wsEnum);
            return vo;

    }


    public static WSVO getReturn(OMElement result, WSEnum wsEnum) {
        if (result != null) {
            Iterator it = result.getChildElements();
            while (it.hasNext()) {
                OMElement c = (OMElement) it.next();
                if ("return".equals(c.getLocalName())) {
                    String json = c.getText();
//                    WSVO vo = JSONUtils.toObject(json, WSVO.class);
                    WSVO vo = JSONObject.parseObject(json,WSVO.class);
                    if (vo == null) {
                        vo = new WSVO();
                        vo.setContent(new ArrayList<>());
                        vo.setMessage("调用NC同步出错");
                        vo.setStatus(false);
                        logger.error(vo.getMessage() + "：" + result.toString());
                    } else if (vo.getContent() == null || vo.getContent().size() == 0 ) {
                        if (StrUtil.isNotBlank(vo.getMessage()) && vo.getMessage().contains("成功")) {
                            vo.setStatus(true);
                        } else {
                            vo.setStatus(false);
                        }
                        vo.setContent(new ArrayList<>());
                        logger.error(vo.getMessage() + "：" + result.toString());
                    } else {
                     //   RedisUtil.set(wsEnum.getRediskey(), SUtil.getnowTime());
                    }
                    if (StrUtil.isNotBlank(vo.getMessage())) {
                        vo.setMessage(vo.getMessage().replaceAll(":", "：").replaceAll("\"", "“").replaceAll("null", "__"));
                    }
                    return vo;
                } else {
                    System.out.println(c.getLocalName() + "——" + c.getText());
                }
            }
        }
        return null;
    }

    private void saveLog(String method, String log) {
/*        Bd_Visit visit = new Bd_Visit();
        visit.setIp("local");
        visit.setUrl(method);
        visit.setUserid(SessionUtil.getCurrenUser().getId());
        visit.setUsername(SessionUtil.getCurrenUser().getUsername());
        visit.setCreatetime(SUtil.getnowTime());
        log = log.replaceAll("null", "_").replaceAll("NULL", "__");
        visit.setEquipmentno(log.length() > 2500 ? log.substring(0, 1500) : log);
        LogJob.putLog(visit);*/
    }

}
